package com.qhad.ads.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.qh.feeds.FeedItem;
import com.qh.feeds.FeedsLoader;
import com.qh.feeds.FeedsLoaderCallback;
import com.qh.feeds.MFeedItem;
import com.songheng.eastnews.apk.R;
import com.qhad.ads.sdk.adcore.Qhad;
import com.qhad.ads.sdk.interfaces.IQhAdEventListener;
import com.qhad.ads.sdk.log.QHADLog;

import java.io.InputStream;
import java.util.ArrayList;


public class NativeBannerInListViewActivity extends Activity {

    int height, width = 0;
    private RelativeLayout lvContainer;
    private boolean isGot = false;
    private EditText etAspW;
    private EditText etAspH;
    private int containerWidth;
    private Button btnSet;
    private Button btnLoad;
    private ListView.LayoutParams listviewlp;
    private MAdapter adapter;

    private int[] adpositions = {1, 5};
    private ArrayList<RelativeLayout> adviews;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Qhad.setLogSwitch(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nativebanner_listview);

        setTitle("嵌入式广告");

        etAspW = (EditText) findViewById(R.id.etAspRateW);
        etAspH = (EditText) findViewById(R.id.etAspRateH);
        etAspW.setEnabled(false);
        etAspH.setEnabled(false);

        etAspW.setText(this.getIntent().getStringExtra("width"));
        etAspH.setText(this.getIntent().getStringExtra("height"));


        adviews = new ArrayList<RelativeLayout>();

        for (int i = 0; i < adpositions.length; i++) {
            adviews.add(new RelativeLayout(this));
        }

        lvContainer = (RelativeLayout) findViewById(R.id.lvContainer);
        final ListView listView = new ListView(this);
        RelativeLayout.LayoutParams lvlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        adapter = new MAdapter(this.getApplicationContext(), this);
        listView.setAdapter(adapter);
        lvContainer.addView(listView, lvlp);

//        nbitem_first.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                TextView tvInfo = (TextView) findViewById(R.id.tvViewInfo);
//                tvInfo.setText(String.format("W: %s px,H: %s px", nbitem_first.getMeasuredWidth(), nbitem_first.getMeasuredHeight()));
//            }
//        });

        listView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

//                QHADLog.e(Utils.getCurrentTime() + "      listView onGlobalLayout");
                if (!isGot) {
                    containerWidth = listView.getMeasuredWidth();

                    setWH();

                    getdata();
                    isGot = true;
                }
            }
        });

//        nbitem_first.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                QHADLog.e(Utils.getCurrentTime() + "      nbitme onGlobalLayout");
//            }
//        });

        FeedsLoader.getInstance().load(new FeedsLoaderCallback() {

                                           @Override
                                           public void onLoaded(ArrayList<FeedItem> items) {

                                           }

                                           @Override
                                           public void whenLoaded(final ArrayList<MFeedItem> items) {
                                               new Handler(Looper.getMainLooper()).post(new Runnable() {

                                                                                            @Override
                                                                                            public void run() {
                                                                                                int index = 0;
                                                                                                for (MFeedItem item : items) {

                                                                                                    adapter.addItem(item);

                                                                                                    for (int i = 0; i < adpositions.length; i++) {
                                                                                                        if (index == adpositions[i] - i - 1) {
                                                                                                            MFeedItem item_ad = new MFeedItem();
                                                                                                            item_ad.adview = adviews.get(i);
                                                                                                            item_ad.isAd = true;
                                                                                                            adapter.addItem(item_ad);
                                                                                                        }
                                                                                                    }

                                                                                                    QHADLog.e("index:" + index);
                                                                                                    index++;
                                                                                                }

                                                                                                adapter.notifyDataSetChanged();
                                                                                            }
                                                                                        }
                                               );
                                           }


                                       }

        );
    }

    private void getdata() {

        for (int i = 0; i < adviews.size(); i++) {

            Qhad.showNativeBanner(adviews.get(i), this, "PPub5d0djn", true).setAdEventListener(new IQhAdEventListener() {
                @Override
                public void onAdviewGotAdSucceed() {

                }

                @Override
                public void onAdviewGotAdFail() {
                    adapter.removeItem(adapter.adposition);
                    adapter.notifyDataSetChanged();
                }

                @Override
                public void onAdviewRendered() {

                }

                @Override
                public void onAdviewIntoLandpage() {

                }

                @Override
                public void onAdviewDismissedLandpage() {

                }

                @Override
                public void onAdviewClicked() {

                }

                @Override
                public void onAdviewClosed() {

                }

                @Override
                public void onAdviewDestroyed() {

                }
            });

        }
    }

    private void setWH() {
        double dW = Double.parseDouble(etAspW.getText().toString());
        double dH = Double.parseDouble(etAspH.getText().toString());
        width = containerWidth;
        height = (int) Math.floor(containerWidth * (dH / dW));

        listviewlp = new ListView.LayoutParams(width, height);
        for (int i = 0; i < adviews.size(); i++) {
            adviews.get(i).setLayoutParams(listviewlp);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        /**
         * Acvitivy销毁时调用，回收广告资源
         */
        Qhad.activityDestroy(this);
    }
}

class MAdapter extends BaseAdapter {
    public MFeedItem item;
    public int adposition;
    private ArrayList<MFeedItem> list = new ArrayList<MFeedItem>();
    private Context context;
    private Activity activity;

    public MAdapter(Context context, Activity activity) {
        this.context = context;
        this.activity = activity;
    }

    public void addItem(MFeedItem item) {
        list.add(item);
    }

    public void removeItem(int position) {
        list.remove(position);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == adposition)
            return 1;
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        item = (MFeedItem) this.getItem(position);

        if (item.isAd) {
            QHADLog.e("AD position is:" + position);
            this.adposition = position;
            return item.adview;
        }

        MViewHolder holder = new MViewHolder();
        LayoutInflater inflater = LayoutInflater.from(context);
        if (convertView != null) {
            holder = (MViewHolder) convertView.getTag();
        } else {
            convertView = inflater.inflate(R.layout.feedsitem, null);

            holder.nameTxt = (TextView) convertView.findViewById(R.id.name);
            holder.contentTxt = (TextView) convertView.findViewById(R.id.feedscontent);
            holder.imageView = (ImageView) convertView.findViewById(R.id.icon);

            convertView.setTag(holder);
        }

        // TODO Auto-generated method stub

        QHADLog.e("position is:" + position);

        holder.nameTxt.setText(item.title);
        holder.contentTxt.setText(item.desc);
        holder.imageView.setTag(item.logo);

        new MDownloadImageTask(holder.imageView).execute(item.logo);

        convertView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!item.isAd) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(item.link);
                    intent.setData(content_url);
                    activity.startActivity(intent);
                }
            }
        });

        return convertView;
    }

    public static class MViewHolder {
        public TextView nameTxt;
        public TextView contentTxt;
        public ImageView imageView;
    }

}

class MDownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;
    String url;

    public MDownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        url = urldisplay;
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        if (url == bmImage.getTag()) {
            bmImage.setImageBitmap(result);
        }

    }

}
